<!-- 
	显示：省及省下的区及各县级市
 -->
<template>
	<view class="filter-area" style="border-top: 5rpx solid #F3F4F6; ">
		<scroll-view class="area-left" scroll-y="true">
			<!-- 其它省 item.v -->
			<view class="area-sf" :class="{ active: code === item.k ? true : false }" v-for="(item, index) in collum1"
				:key="index" :code="item.k" @click="() => getCitys(item.k)">
				<u-parse :content="colum1Name(item)"></u-parse>
			</view>
		</scroll-view>
		<!-- 市 -->
		<scroll-view class="area-right" scroll-y="true">
			<!-- 
				全国：全国 
				直辖市：不渲染  
				除直辖市外的显示：不限 
			-->
			<view v-if="clickType !== -1" class="area-province"
				:class="{ active: memoryCitys.includes(code) ? true : false }" v-text="clickType === '' ? '全国' : '不限'"
				@click="() => popCityClick(code, true)"></view>
			<view :key="index" class="area-province" :class="{ active: memoryCitys.includes(item.k) ? true : false }"
				v-for="(item, index) in citys" v-text="item.v" @click="() => popCityClick(item.k)"></view>
		</scroll-view>

		<view class="filter-foot d-f">
			<view class="cancel-btn" @click="reset()">
				<image src="https://img.bidcenter.com.cn/uni/chongzhi.png" class="chongzhiIcon"></image>重置
			</view>
			<view class="confirm-btn" @click="addCityOK(true)">确定 {{ checksNum }}</view>
		</view>
	</view>
</template>

<script>
	/**
	 * 注：areas keys(code)为string，而keys下的数组对应的key(code)是int
	 * 选择城市popup弹窗样式不通用，故只提取 非弹窗中的内容
	 */
	import {
		areas,
		areaMap
	} from '@/util/diction.js';
	export default {
		name: 'diqu',
		/**
		 * form: 来源，from='list': 表明来源于列表页中，按钮样式与订阅页不同
		 * type 类型，默认城市列表 1:区域列表，只能选择省，不能选市
		 * customList: 已订阅列表，只有订阅列表中需要传
		 */
		props: ['initDiqu', 'areaPop', 'from', 'type', 'customList'],
		emits: ['searchFn'],
		data() {
			// type:1 只能选择 区域/省 否则：可以选择省市
			let collum1 = areas['0'];
			//  ["11", "12", "31", "50"] 直辖市下二级直接展示所有区
			// let exclude = ['11', '12', '31', '50', '82', '81', '71'];
			let exclude = [ '82', '81', '71'];

			if (this.type === '1') {
				collum1 = areas['qy']
				exclude = []
			}

			return {
				collum1: collum1,
				// 订阅省List
				// dyProvinceList:[],
				// dyCitysList:[],

				// 添加地区弹窗中点击确认按钮前的暂存 选中城市
				memoryCitys: JSON.parse(JSON.stringify(this.initDiqu)).split(','),

				// 表明所点击的是哪种：全国 '' 省1 直辖市-1
				clickType: '',
				// 所点击 全国/省中的 不限的code
				// 点击项为 全国 '' 时，不获取 ''对应的citys（全部省），直接显示 全国
				code: '',
				shengNum: 0,
				citysNums: 0,
				// 北京，天津，重庆，香港，台湾，澳门， 不显示 全部
				exclude: exclude
			};
		},
		computed: {
			// 省name格式化（显示 全/数量）
			colum1Name: function() {
				return function(item) {
					// item =item;
					if (this.memoryCitys.includes(item.k)) {
						item.num = '全';
					} else {
						item.num = 0;
						// 全国则不遍历，全国下无城市数组
						if (item.k !== '') {
							// 遍历省下的城市数目
							let n = 0;
							areas[item.k + ''] && areas[item.k + ''].map(m => {
								if (this.memoryCitys.includes(m.k)) {
									n = n + 1;
								}
							})
							item.num = n;
						}
					}
					if (!!item.num) {
						return item.v + '<view class="area-num">' + item.num + '</view>'
					} else {
						// 更新collum1，注：只有订阅列表页中用到，筛选下拉中只显示已订阅过的省
						return item.v
					}

				}

			},

			// 模式：省/市
			numMap: function() {
				const obj = {};
				let shengN = 0,
					delCitys = 0;
				this.collum1.map(item => {
					if (this.memoryCitys.includes(item.k)) {
						++shengN;
						areas[item.k + ''] && areas[item.k + ''].map(m => {
							if (this.memoryCitys.includes(m.k)) {
								++delCitys;
							}
						});
					}
				});
				obj.sheng = shengN;
				obj.city = this.memoryCitys.length - shengN - delCitys;
				return obj;
			},
			// 模式：区域/省
			numMap2: function() {
				const obj = {};
				let shengN = 0;
				this.collum1.map(item => {
					if (this.memoryCitys.includes(item.k)) {
						shengN++;
					}
				});
				obj.sheng = shengN;
				obj.city = this.memoryCitys.length - shengN;
				return obj;
			},

			citys: function() {
				const citys = [];
				// 订阅列表页：筛选下拉只显示已订阅的市
				if (this.customList && this.customList.length && this.customList[0] !== '') {
					// 订阅全部市
					if (this.customList.includes(this.code)) {
						areas[this.code].map((item, i) => {
							citys.push(item);
						});
					} else {
						// 订阅部分市
						this.code && areas[this.code].map((item, i) => {
							if (this.customList.includes(item.k)) {
								citys.push(item);
							}
						})
					}

					return citys;
				} else {
					// 非订阅列表页中或订阅为默认值全国时
					// 点击项为 全国 0 时，不获取 0对应的citys（全部省），直接显示 全国
					if (this.code === '') {
						return [];
					} else {
						const citys = [];
						areas[this.code].map((item, i) => {
							citys.push(item);
						});
						return citys;
					}
				}
			},

			checksNum: function() {
				const len = this.memoryCitys.length;
				// 模式为省/市
				if (this.type !== '1') {
					const numMap = this.numMap;
					const {
						sheng,
						city
					} = numMap;
					if (len) {
						if (len === 1 && this.memoryCitys[0] === '') {
							return `(已选 全国)`;
						} else if (sheng > 0 && city > 0) {
							return `(已选 ${sheng}个省 ${city}个市)`;
						} else if (sheng > 0 && city === 0) {
							return `(已选 ${sheng}个省)`;
						} else if (sheng === 0 && city > 0) {
							return `(已选 ${city}个市)`;
						}
					}
				} else {
					// 模式为 区域/省
					const numMap = this.numMap2;
					const {
						sheng,
						city
					} = numMap;
					if (len) {
						if (len === 1 && this.memoryCitys[0] === '') {
							return `(已选 全国)`;
						} else if (city > 0) {
							return `(已选 ${city}个省)`;
						}
					}
				}
			}
		},
		watch: {
			initDiqu(a, b) {
				if (a !== b) {
					this.memoryCitys = a.split(',')
					this.init()
				}
			},
			customList: {
				handler(a, b) {
					if (a && a[0] === '') {
						this.collum1 = areas[0]
						// this.$emit('update:initDiqu', '')
						// this.$emit('update:customList', [''])
						this.memoryCitys = ['']
						this.code = ''
						this.clickType = ''
						return
					} else {
						const shenglist = [];
						areas['0'].map(item => {
							if (this.memoryCitys.includes(item.k)) {
								shenglist.push(item);
							} else {
								areas[item.k] && areas[item.k].map(m => {
									if (this.memoryCitys.includes(m.k)) {
										const shenglistkeys = []
										shenglist.map(x => {
											shenglistkeys.push(x.k)
										})
										if (!shenglistkeys.includes(item.k)) {
											shenglist.push(item);
										}
									}
								})
							}
						})
						// 订阅列表页筛选下拉只显示已订阅项
						if (a.length && this.type !== '1') {
							this.collum1 = shenglist;
						}
					}
				},
				immediate: false,
			}
		},

		methods: {
			// 更新状态
			init() {
				// this.memoryCitys = this.memoryCitys.filter(item => item !== '')
				// this.memoryCitys = this.memoryCitys.map(item => {
				// 	return item !== '' ? item : '';
				// });

				if (this.memoryCitys.length === 1 && this.memoryCitys[0] === '') {
					this.code = '';
					this.clickType = '';
				} else {
					const checkcity = this.memoryCitys[this.memoryCitys.length - 1];
					const {
						exclude
					} = this;
					this.collum1.slice(1).map(item => {
						if (item.k === checkcity) {
							this.clickType = exclude.includes(item.k) ? -1 : 1;
							this.code = item.k;
						} else {
							areas[item.k + ''] &&
								areas[item.k + ''].map(m => {
									if (m.k === checkcity) {
										this.clickType = exclude.includes(item.k) ? -1 : 1;
										this.code = item.k;
									}
								});
						}
					});

					// 若选中项中有省，则更新省下的所有城市为 checked 状态
					this.collum1.map(item => {
						if (this.memoryCitys.includes(item.k)) {
							areas[item.k + ''].map(m => {
								this.memoryCitys.push(m.k);
							});
						}
					});
				}
				if (this.type !== 1 && this.customList && this.customList[0] !== '') {
					this.isShowBuxian();
				}

			},

			/**
			 * 是否显示 不限
			 * 订阅列表页：筛选下拉只显示已订阅的市，如果选中了部分城市，隐藏 不限
			 */
			isShowBuxian() {
				if (!this.customList.includes(this.code)) {
					this.clickType = -1
				}
			},

			// 根据省接口获取市
			getCitys(code) {
				this.code = code;

				if (this.exclude.includes(code)) {
					this.clickType = -1;
				} else {
					if (code === '') {
						this.clickType = '';
					} else {
						this.clickType = 1;
					}
				}
				if (this.type !== 1 && this.customList && this.customList[0] !== '') {
					this.isShowBuxian();
				}

			},

			popCityClick(code, isall = false) {
				// 点击不限 或者 全国
				if (isall) {
					if (code === '') {
						if (this.memoryCitys.includes(code)) {
							this.memoryCitys = this.memoryCitys.filter(item => item !== code);
						} else {
							this.memoryCitys = [''];
						}
					} else {
						// 点击 不限
						// 不限已选中时
						if (this.memoryCitys.includes(code)) {
							this.memoryCitys = this.memoryCitys.filter(item => item !== code);

							this.citys.map(item => {
								this.memoryCitys = this.memoryCitys.filter(m => m !== item.k);
							});
						} else {
							// 不限未选中时
							// 如果 全国 已选中，则清除
							if (this.memoryCitys.includes('')) {
								this.memoryCitys = this.memoryCitys.filter(item => item !== '');
							}

							this.memoryCitys.push(code);
							this.citys.map(item => {
								if (!this.memoryCitys.includes(item.k)) {
									this.memoryCitys.push(item.k);
								}
							});
						}
					}
				} else {
					// 点击非 不限或全国
					// 如果 全国 已选中，则清除
					if (this.memoryCitys.includes('')) {
						this.memoryCitys = this.memoryCitys.filter(item => item !== '');
					}

					if (this.memoryCitys.includes(code)) {
						this.memoryCitys = this.memoryCitys.filter(item => item !== code);
						// 移除 不限
						if (this.memoryCitys.includes(this.code)) {
							this.memoryCitys = this.memoryCitys.filter(item => item !== this.code);
						}
					} else {
						this.memoryCitys.push(code);

						if (this.exclude.includes(code)) return;

						// 如果点击后所有市都选中，则默认勾选 不限
						const num = areas[this.code + ''].length;
						let cur = 0;

						areas[this.code + ''].map(item => {
							if (this.memoryCitys.includes(item.k)) {
								++cur;
							}
						});
						if (cur === num) {
							this.memoryCitys.push(this.code);
						}
					}
				}
			},

			// 添加地区，确认功能
			addCityOK(isHasEmit = false) {
				// isHasEmit 点击完确认按钮后是否要触发实例上的方法，默认false,搜索列表页需要触发搜索接口
				// uni.showTabBar()

				// 模式为 省/市：过滤掉选中省下的城市 （全部时：显示省名称，不显示所有的市名称）
				if (this.type !== '1') {
					this.collum1.map(item => {
						if (this.memoryCitys.includes(item.k)) {
							areas[item.k + ''] && areas[item.k + ''].map(m => {
								if (this.memoryCitys.includes(m.k)) {
									this.memoryCitys = this.memoryCitys.filter(x => x !== m.k);
								}
							});
						}
					});
				} else {
					// 模式为 区域/省 （全部时：显示所有省的名称）
					this.collum1.map(item => {
						if (this.memoryCitys.includes(item.k)) {
							this.memoryCitys = this.memoryCitys.filter(x => x !== item.k);
						}
					});
				}

				if (!this.memoryCitys.length) {
					this.memoryCitys = [''];
				}

				// 关闭popup
				this.$emit('update:areaPop', false);
				this.$emit('update:initDiqu', this.memoryCitys.join(','));
				if (isHasEmit) {
					this.$emit('searchFn',{page:1});
				}
			},
			// 重置
			reset() {
				this.getCitys('');
				this.memoryCitys = [''];
			},
			// 列表页中用到
			closeAreaPop() {
				this.$emit('update:areaPop', false);
			}
		},
	};
</script>

<style lang="scss">
	// 地区Pop中的 全 图标
	::v-deep .area-num {
		width: 34rpx;
		height: 34rpx;
		background-color: #2f6dfe;
		border-radius: 50%;
		color: #ffffff;
		font-size: 22rpx;
		text-align: center;
		line-height: 34rpx;
		position: absolute;
		right: 30rpx;
		top: 26rpx;
	}
	
	.chongzhiIcon {
	  width: 40rpx;
	  height: 40rpx;
	  margin-right: 6rpx;
	}
	.filter-area {
		padding: 0;
		padding-bottom: 140rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.area-left,
		.area-right {
			height: 686rpx;
			// padding: 20rpx 0;
		}
		.area-left {
			width: 285rpx;
			background-color: #f4f6f6;
			// padding: 20rpx 0;
			box-sizing: border-box;
			.area-sf {
				padding: 24rpx 27rpx;
				font-size: 24rpx;
				position: relative;
				&.active {
					// background-color: #fbefe1;
					background-color: #fff;
					color: #2f6dfe;
				}
			}
		}
		.area-right {
			padding: 20rpx;
			box-sizing: border-box;
			flex: 1;
			padding-right: 0;
			overflow: auto;
			.area-all {
				background-color: #f7f7f7;
				height: 57rpx;
				width: 45%;
				color: #3b3e45;
				font-size: 26rpx;
				margin-bottom: 20rpx;
			}
			.area-province {
				background-color: #f7f7f7;
				height: 57rpx;
				// width: 127rpx;
				width: 45%;
				color: #3b3e45;
				font-size: 24rpx;
				margin-bottom: 20rpx;
				margin-right: 20rpx;
				padding: 0 4rpx;
				display: inline-block;
				text-align: center;
				line-height: 57rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				border: 1px solid #f7f7f7;
				box-sizing: border-box;
				border-radius: 6rpx;
				&.active {
					background: rgba(47, 109, 254, 0.06);
					// color: #106CFF;
					// background-color: #fbefe1;
					color: #2f6dfe;
					border-radius: 6rpx;
					border: 1rpx solid #2478fe;
					box-sizing: border-box;
				}
			}
		}
	}
	
	.filter-foot {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		border-top: 1px solid #eee;
		.cancel-btn {
			width: 160rpx;
			height: 98rpx;
			line-height: 98rpx;
			text-align: center;
			background-color: #ffffff;
			color: #999999;
			font-size: 30rpx;
			border-bottom-left-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.confirm-btn {
			flex: 1;
			height: 98rpx;
			line-height: 98rpx;
			text-align: center;
			// background-color: #2F6DFE;
			// background-color: #00bbff;
			background: linear-gradient(90deg, #1f91ff 0%, #1d11fb 100%);
			color: #ffffff;
			font-size: 30rpx;
			border-radius: 10rpx;
			// margin-right:20rpx;
		}
	}

	.citysWrap {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;

		.cancel-btn {
			width: 40%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #f4f6f7;
			color: #999999;
			font-size: 30rpx;
			// display: flex;
			// align-items: center;
		}

		.confirm-btn {
			width: 60%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #ff6917;
			color: #ffffff;
			font-size: 30rpx;
		}
	}
</style>